// led.c
// 控制LED灯
#include "freertos/FreeRTOS.h"  // xTaskCreate
#include "driver/gpio.h"  // gpio_config
#include "esp_err.h"  // ESP_ERROR_CHECK
#include "esp_log.h" // ESP_LOGI
#include "common.h"

// 暴露变量
TaskHandle_t led_handle = NULL;

// 内部变量
static const char *TAG = "LED";

// LED 任务
void led_task(void *arg) {
  /*--------初始化--------*/
  gpio_config_t io_config = {  // 配置led
    .mode = GPIO_MODE_OUTPUT,
    .pull_up_en = GPIO_PULLUP_DISABLE,
    .pull_down_en = GPIO_PULLDOWN_DISABLE,
    .intr_type = GPIO_INTR_DISABLE,
    .pin_bit_mask = (1ULL << LED_PIN),
  };
  ESP_ERROR_CHECK(gpio_config(&io_config));
  ESP_ERROR_CHECK(gpio_set_level(LED_PIN, 1));  // 默认关 1灭0亮
  ESP_LOGI(TAG, "init finish.");
  /*--------LED逻辑--------*/
  while (true) {
    xTaskNotifyWait(0, 0, NULL, portMAX_DELAY);
    ESP_LOGI(TAG, "state: %s.", switch_state == 1 ? "on" : "off");
    if (switch_state == 1) {  // 开
      ESP_ERROR_CHECK(gpio_set_level(LED_PIN, 0));
      ESP_LOGI(TAG, "led started.");
    } else {  // 关
      ESP_ERROR_CHECK(gpio_set_level(LED_PIN, 1));
      ESP_LOGI(TAG, "led stopped.");
    }
    xTaskNotify(switch_handle, 0, eNoAction);
  }
}
